/**
 * 作者工作台功能
 */

let currentNovelId = null;
let currentChapterId = null;
let authorNovels = [];
let currentPage = 1;  // 添加当前页码
let pageSize = 10;    // 添加每页大小
let totalPages = 0;   // 添加总页数

// 页面加载完成后执行
$(document).ready(function() {
    // 加载作者数据
    loadAuthorStats();
    loadAuthorNovels();
    // loadCategories(); // 移除：不再在页面加载时加载分类
    
    // 绑定事件
    bindEvents();
});

/**
 * 绑定事件处理
 */
function bindEvents() {
    // 搜索作品
    $('#searchNovels').on('input', function() {
        filterNovels();
    });
    
    // 状态筛选
    $('#statusFilter').on('change', function() {
        filterNovels();
    });
    
    // 章节内容字数统计
    $('#chapterContent').on('input', function() {
        updateWordCount();
    });
    
    // 封面预览
    $('#novelCover').on('change', function() {
        previewCover(this);
    });
}

/**
 * 加载作者统计数据
 */
function loadAuthorStats() {
    $.ajax({
        url: '/demo1_war_exploded/API/Author/statistics',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.code === 200) {
                const stats = response.data;
                $('#totalNovels').text(stats.totalNovels || 0);
                $('#totalChapters').text(stats.totalChapters || 0);
                $('#totalReads').text(formatNumber(stats.totalReads || 0));
                $('#totalFans').text(stats.totalFans || 0);
            }
        },
        error: function() {
            console.error('加载统计数据失败');
        }
    });
}

/**
 * 加载作者作品列表
 */
function loadAuthorNovels(pageNum = 1, status = '', keyword = '') {
    showLoading();
    
    $.ajax({
        url: '/demo1_war_exploded/API/Author/novels',
        type: 'GET',
        data: {
            pageNum: pageNum,
            pageSize: pageSize,
            status: status,
            keyword: keyword
        },
        dataType: 'json',
        success: function(response) {
            hideLoading();
            
            if (response.code === 200) {
                authorNovels = response.rows || [];
                currentPage = response.pageNum || 1;
                totalPages = Math.ceil(response.total / pageSize);
                
                renderNovels(authorNovels);
                renderPagination(response.total, currentPage, pageSize);
            } else {
                showError(response.msg || '加载作品失败');
            }
        },
        error: function() {
            hideLoading();
            showError('网络错误，请稍后重试');
        }
    });
}

/**
 * 渲染作品列表
 */
function renderNovels(novels) {
    const container = $('#novelsContainer');
    container.empty();
    
    if (!novels || novels.length === 0) {
        $('#emptyNovels').show();
        return;
    }
    
    $('#emptyNovels').hide();
    
    novels.forEach(novel => {
        const novelItem = createNovelItem(novel);
        container.append(novelItem);
    });
}

/**
 * 创建作品项
 */
function createNovelItem(novel) {
    const statusColor = getStatusColor(novel.status);
    const lastUpdate = novel.last_update ? new Date(novel.last_update).toLocaleDateString() : '未更新';
    
    return $(`
        <div class="novel-item border-bottom p-3">
            <div class="row align-items-center">
                <div class="col-md-2">
                    <img src="${novel.cover_url || 'https://mysteriouslamb.oss-cn-hangzhou.aliyuncs.com/icon.jpg'}" 
                         alt="${novel.novel_name}" class="img-fluid rounded" style="max-height: 80px;">
                </div>
                <div class="col-md-4">
                    <h6 class="mb-1">${novel.novel_name}</h6>
                    <p class="text-muted small mb-1">${novel.category || '未分类'}</p>
                    <span class="badge ${statusColor} status-badge">${novel.status || '连载中'}</span>
                </div>
                <div class="col-md-3">
                    <div class="small text-muted">
                        <div>章节数: ${novel.chapter_count || 0}</div>
                        <div>阅读量: ${formatNumber(novel.read_count || 0)}</div>
                        <div>最后更新: ${lastUpdate}</div>
                    </div>
                </div>
                <div class="col-md-3 text-end">
                    <button class="btn btn-sm btn-outline-primary me-1" 
                            onclick="manageChapters(${novel.novel_id})">
                        <i class="bi bi-list-ul"></i> 章节管理
                    </button>
                    <button class="btn btn-sm btn-outline-success me-1" 
                            onclick="editNovel(${novel.novel_id})">
                        <i class="bi bi-pencil"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-outline-info" 
                            onclick="viewStats(${novel.novel_id})">
                        <i class="bi bi-graph-up"></i> 数据
                    </button>
                </div>
            </div>
        </div>
    `);
}

/**
 * 获取状态颜色
 */
function getStatusColor(status) {
    switch(status) {
        case '连载中': return 'bg-success';
        case '已完结': return 'bg-primary';
        case '暂停': return 'bg-warning';
        default: return 'bg-secondary';
    }
}

/**
 * 显示创建作品模态框
 */
function showCreateNovelModal() {
    $('#createNovelForm')[0].reset();
    $('#coverPreview').attr('src', 'https://mysteriouslamb.oss-cn-hangzhou.aliyuncs.com/novel/a50d6dafc1d6a8c8846145bb24b9728.png');
    
    loadCategories(); // 新增：在显示模态框时加载分类数据

    const modal = new bootstrap.Modal(document.getElementById('createNovelModal'));
    modal.show();
}

/**
 * 创建作品
 */
function createNovel() {
    const formData = new FormData();
    formData.append('novel_name', $('#novelTitle').val().trim());
    formData.append('introduction', $('#novelIntro').val().trim());
    formData.append('novel_tags', $('#novelTags').val().trim());
    
    // 获取选中的分类ID数组
    const selectedCategories = [];
    $('input[name="novelCategory"]:checked').each(function() {
        selectedCategories.push($(this).val());
    });
    
    // 将分类ID数组作为JSON字符串发送
    if (selectedCategories.length > 0) {
        formData.append('categoryIds', JSON.stringify(selectedCategories));
    }
    
    // 处理封面文件上传
    const coverFile = $('#novelCover')[0].files[0];
    if (coverFile) {
        formData.append('coverFile', coverFile);
    }
    
    // 验证逻辑
    if (!$('#novelTitle').val().trim()) {
        showError('请输入作品标题');
        return;
    }
    
    if (selectedCategories.length === 0) {
        showError('请选择作品分类');
        return;
    }
    
    if (!$('#novelIntro').val().trim()) {
        showError('请输入作品简介');
        return;
    }
    
    $.ajax({
        url: '/demo1_war_exploded/API/Author/create',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.code === 200) {
                bootstrap.Modal.getInstance(document.getElementById('createNovelModal')).hide();
                showSuccess('作品创建成功');
                loadAuthorNovels();
                loadAuthorStats();
            } else {
                showError(response.msg || '创建失败');
            }
        },
        error: function() {
            showError('网络错误，请稍后重试');
        }
    });
}

/**
 * 管理章节
 */
function manageChapters(novelId) {
    currentNovelId = novelId;
    const novel = authorNovels.find(n => n.novel_id === novelId);
    
    if (novel) {
        $('#chapterModalLabel').text(`《${novel.novel_name}》- 章节管理`);
        loadChapterList(novelId);
        
        const modal = new bootstrap.Modal(document.getElementById('chapterModal'));
        modal.show();
    }
}

/**
 * 加载章节列表
 */
function loadChapterList(novelId) {
    $.ajax({
        url: '/demo1_war_exploded/API/Chapter?novelId=' + novelId,
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.code === 200) {
                renderChapterList(response.data || []);
            } else {
                showError('加载章节失败');
            }
        },
        error: function() {
            showError('网络错误，请稍后重试');
        }
    });
}

/**
 * 渲染章节列表 - 支持分卷显示和删除草稿
 */
function renderChapterList(chapters) {
    const container = $('#chapterList');
    container.empty();
    
    if (chapters.length === 0) {
        container.html('<p class="text-muted text-center">暂无章节</p>');
        return;
    }
    
    // 按分卷分组章节
    const volumeGroups = {};
    chapters.forEach(chapter => {
        const volumeName = chapter.volume_name || '未分卷';
        if (!volumeGroups[volumeName]) {
            volumeGroups[volumeName] = [];
        }
        volumeGroups[volumeName].push(chapter);
    });
    
    // 渲染每个分卷
    Object.keys(volumeGroups).forEach(volumeName => {
        const volumeChapters = volumeGroups[volumeName];
        
        // 分卷标题
        const volumeHeader = $(`
            <div class="volume-header mb-3">
                <h6 class="text-primary fw-bold border-bottom pb-2">
                    <i class="bi bi-collection"></i> ${volumeName}
                    <span class="badge bg-secondary ms-2">${volumeChapters.length}章</span>
                </h6>
            </div>
        `);
        container.append(volumeHeader);
        
        // 分卷下的章节
        volumeChapters.forEach(chapter => {
            const isDraft = chapter.chapter_status === 1; // 假设1为草稿状态
            const statusText = isDraft ? '草稿' : '已发布';
            const statusClass = isDraft ? 'bg-warning' : 'bg-success';
            
            const chapterItem = $(`
                <div class="chapter-item p-3 border rounded mb-2 ms-3" 
                     data-chapter-id="${chapter.chapter_id}">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="flex-grow-1 cursor-pointer" onclick="openChapterEditor(${chapter.chapter_id})">
                            <div class="fw-bold">第${chapter.chapter_number}章 ${chapter.chapter_title}</div>
                            <small class="text-muted">
                                ${formatDate(chapter.update_time)} | ${chapter.word_count || 0}字
                            </small>
                        </div>
                        <div class="text-end">
                            <span class="badge ${statusClass} small mb-2">${statusText}</span>
                            <div>
                                <button class="btn btn-sm btn-outline-primary me-1" 
                                        onclick="openChapterEditor(${chapter.chapter_id})" 
                                        title="编辑章节">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                ${isDraft ? `
                                    <button class="btn btn-sm btn-outline-danger" 
                                            onclick="deleteDraft(${chapter.chapter_id}, '${chapter.chapter_title}')" 
                                            title="删除草稿">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            `);
            container.append(chapterItem);
        });
    });
}

/**
 * 删除草稿章节
 */
function deleteDraft(chapterId, chapterTitle) {
    if (!confirm(`确定要删除草稿章节《${chapterTitle}》吗？此操作不可恢复。`)) {
        return;
    }
    
    $.ajax({
        url: `/demo1_war_exploded/API/Chapter/${chapterId}`,
        type: 'DELETE',
        dataType: 'json',
        success: function(response) {
            if (response.code === 200) {
                showSuccess('草稿删除成功');
                loadChapterList(currentNovelId); // 重新加载章节列表
                loadAuthorStats(); // 更新统计数据
            } else {
                showError(response.msg || '删除失败');
            }
        },
        error: function() {
            showError('网络错误，请稍后重试');
        }
    });
}

/**
 * 打开章节编辑器
 */
function openChapterEditor(chapterId) {
    // 获取章节信息以获取分卷名称
    const chapterElement = $(`.chapter-item[data-chapter-id="${chapterId}"]`);
    const volumeHeader = chapterElement.prevAll('.volume-header').first();
    let volumeName = '';
    
    if (volumeHeader.length > 0) {
        // 从分卷标题中提取分卷名称
        const volumeText = volumeHeader.find('h6').text();
        volumeName = volumeText.replace(/^.*?\s/, '').replace(/\s+\d+章$/, '').trim();
    }
    
    const url = `/demo1_war_exploded/MainPage/functionPage/chapterEditor.jsp?novelId=${currentNovelId}&chapterId=${chapterId}&volumeName=${encodeURIComponent(volumeName)}`;
    window.open(url, '_blank');
}

/**
 * 创建新章节
 */
function createNewChapter() {
    // 获取最后一章的分卷信息
    let lastVolumeName = '';
    const volumeHeaders = $('.volume-header');
    
    if (volumeHeaders.length > 0) {
        const lastVolumeHeader = volumeHeaders.last();
        const volumeText = lastVolumeHeader.find('h6').text();
        lastVolumeName = volumeText.replace(/^.*?\s/, '').replace(/\s+\d+章$/, '').trim();
    }
    
    const url = `/demo1_war_exploded/MainPage/functionPage/chapterEditor.jsp?novelId=${currentNovelId}&new=true&volumeName=${encodeURIComponent(lastVolumeName)}`;
    window.open(url, '_blank');
}

/**
 * 格式化日期
 */
function formatDate(dateString) {
    if (!dateString) return '未知时间';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
}

/**
 * 封面预览
 */
function previewCover(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            $('#coverPreview').attr('src', e.target.result);
        };
        reader.readAsDataURL(input.files[0]);
    }
}

/**
 * 筛选作品
 */
function filterNovels() {
    const searchText = $('#searchNovels').val();
    const statusFilter = $('#statusFilter').val();
    
    // 重置到第一页并重新加载
    loadAuthorNovels(1, statusFilter, searchText);
}

/**
 * 刷新作品列表
 */
function refreshNovels() {
    const statusFilter = $('#statusFilter').val();
    const searchText = $('#searchNovels').val();
    loadAuthorNovels(currentPage, statusFilter, searchText);
}

/**
 * 渲染分页
 * @param {number} total - 总数量
 * @param {number} currentPage - 当前页码
 * @param {number} pageSize - 每页数量
 */
function renderPagination(total, currentPage, pageSize) {
    const totalPages = Math.ceil(total / pageSize);
    
    // 如果只有一页或没有数据，不显示分页
    if (totalPages <= 1) {
        $('#pagination-container').empty();
        return;
    }
    
    // 创建分页HTML
    let paginationHTML = `
        <nav aria-label="作品分页">
            <ul class="pagination justify-content-center">
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" data-page="${currentPage - 1}" aria-label="上一页">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
    `;
    
    // 计算显示的页码范围
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, startPage + 4);
    
    // 调整起始页，确保显示5个页码
    if (endPage - startPage < 4) {
        startPage = Math.max(1, endPage - 4);
    }
    
    // 生成页码
    for (let i = startPage; i <= endPage; i++) {
        paginationHTML += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" data-page="${i}">${i}</a>
            </li>
        `;
    }
    
    paginationHTML += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" data-page="${currentPage + 1}" aria-label="下一页">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
    `;
    
    // 设置分页HTML
    $('#pagination-container').html(paginationHTML);
    
    // 添加分页点击事件
    $('.page-link').on('click', function(e) {
        e.preventDefault();
        const page = parseInt($(this).data('page'));
        if (page && page !== currentPage) {
            const statusFilter = $('#statusFilter').val();
            const searchText = $('#searchNovels').val();
            loadAuthorNovels(page, statusFilter, searchText);
        }
    });
}

/**
 * 格式化数字
 */
function formatNumber(num) {
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
}

/**
 * 显示加载状态
 */
function showLoading() {
    console.log('加载中...');
}

/**
 * 隐藏加载状态
 */
function hideLoading() {
    console.log('加载完成');
}

/**
 * 显示错误信息
 */
function showError(message) {
    console.error('错误:', message);
    alert(message);
}

/**
 * 显示成功信息
 */
function showSuccess(message) {
    console.log('成功:', message);
    alert(message);
}


/**
 * 加载分类数据
 */
function loadCategories() {
    $.ajax({
        url: '/demo1_war_exploded/API/Category',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.code === 200) {
                const categories = response.rows || []; // 使用 response.rows
                const categoryContainer = $('#novelCategory');
                categoryContainer.empty();
                
                // 按父分类分组
                const parentCategories = categories.filter(cat => !cat.parent_id || cat.parent_id === null);
                const childCategories = categories.filter(cat => cat.parent_id && cat.parent_id !== null);
                
                parentCategories.forEach(parentCat => {
                    // 添加父分类标题
                    categoryContainer.append(`
                        <div class="mb-2">
                            <strong class="text-primary">${parentCat.category_name}</strong>
                        </div>
                    `);
                    
                    // 添加子分类复选框
                    const children = childCategories.filter(child => child.parent_id == parentCat.category_id);
                    const childrenHtml = children.map(child => `
                        <div class="form-check form-check-inline me-3 mb-2">
                            <input class="form-check-input" type="checkbox" 
                                   id="category_${child.category_id}" 
                                   value="${child.category_id}" 
                                   name="novelCategory">
                            <label class="form-check-label" for="category_${child.category_id}">
                                ${child.category_name}
                            </label>
                        </div>
                    `).join('');
                    
                    categoryContainer.append(`
                        <div class="ms-3 mb-3">
                            ${childrenHtml}
                        </div>
                    `);
                });
            } else {
                console.error('加载分类失败:', response.msg);
            }
        },
        error: function() {
            console.error('网络错误，加载分类失败');
        }
    });
}


/**
 * 编辑作品
 */
function editNovel(novelId) {
    // 调用 /API/Bookshelf/id 获取书籍信息
    $.ajax({
        url: `/demo1_war_exploded/API/Bookshelf/${novelId}`,
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.code === 200) {
                const novel = response.data;
                
                // 填充表单数据
                $('#editNovelId').val(novel.novel_id);
                $('#editNovelTitle').val(novel.novel_name);
                $('#editNovelTags').val(novel.novel_tags || '');
                $('#editNovelStatus').val(novel.status || '连载中');
                $('#editNovelIntro').val(novel.introduction || '');
                
                // 设置封面预览
                const coverUrl = novel.cover_url || 'https://mysteriouslamb.oss-cn-hangzhou.aliyuncs.com/icon.jpg';
                $('#editCoverPreview').attr('src', coverUrl);
                
                // 加载分类数据并设置选中状态
                loadCategoriesForEdit(novel.categoryIds);
                
                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('editNovelModal'));
                modal.show();
            } else {
                showError(response.msg || '获取作品信息失败');
            }
        },
        error: function() {
            showError('网络错误，请稍后重试');
        }
    });
}

/**
 * 为编辑模态框加载分类数据
 */
function loadCategoriesForEdit(selectedCategoryIds) {
    $.ajax({
        url: '/demo1_war_exploded/API/Category',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.code === 200) {
                const categories = response.rows || [];
                const categoryContainer = $('#editNovelCategory');
                categoryContainer.empty();
                
                // 解析已选中的分类ID
                let selectedIds = [];
                if (selectedCategoryIds) {
                    try {
                        selectedIds = typeof selectedCategoryIds === 'string' ? 
                            JSON.parse(selectedCategoryIds) : selectedCategoryIds;
                    } catch (e) {
                        console.warn('解析分类ID失败:', e);
                    }
                }
                
                // 按父分类分组
                const parentCategories = categories.filter(cat => !cat.parent_id || cat.parent_id === null);
                const childCategories = categories.filter(cat => cat.parent_id && cat.parent_id !== null);
                
                parentCategories.forEach(parentCat => {
                    // 添加父分类标题
                    categoryContainer.append(`
                        <div class="mb-2">
                            <strong class="text-primary">${parentCat.category_name}</strong>
                        </div>
                    `);
                    
                    // 添加子分类复选框
                    const children = childCategories.filter(child => child.parent_id == parentCat.category_id);
                    const childrenHtml = children.map(child => {
                        const isChecked = selectedIds.includes(child.category_id) ? 'checked' : '';
                        return `
                            <div class="form-check form-check-inline me-3 mb-2">
                                <input class="form-check-input" type="checkbox" 
                                       id="edit_category_${child.category_id}" 
                                       value="${child.category_id}" 
                                       name="editNovelCategory" ${isChecked}>
                                <label class="form-check-label" for="edit_category_${child.category_id}">
                                    ${child.category_name}
                                </label>
                            </div>
                        `;
                    }).join('');
                    
                    categoryContainer.append(`
                        <div class="ms-3 mb-3">
                            ${childrenHtml}
                        </div>
                    `);
                });
            } else {
                console.error('加载分类失败:', response.msg);
            }
        },
        error: function() {
            console.error('网络错误，加载分类失败');
        }
    });
}

/**
 * 编辑封面预览
 */
function previewEditCover(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            $('#editCoverPreview').attr('src', e.target.result);
        };
        reader.readAsDataURL(input.files[0]);
    }
}

/**
 * 更新作品信息
 */
function updateNovel() {
    const novelId = $('#editNovelId').val();
    const formData = new FormData();
    
    formData.append('novel_name', $('#editNovelTitle').val().trim());
    formData.append('introduction', $('#editNovelIntro').val().trim());
    formData.append('novel_tags', $('#editNovelTags').val().trim());
    formData.append('status', $('#editNovelStatus').val());
    
    // 获取选中的分类ID数组
    const selectedCategories = [];
    $('input[name="editNovelCategory"]:checked').each(function() {
        selectedCategories.push($(this).val());
    });
    
    // 将分类ID数组作为JSON字符串发送
    if (selectedCategories.length > 0) {
        formData.append('categoryIds', JSON.stringify(selectedCategories));
    }
    
    // 处理封面文件上传
    const coverFile = $('#editNovelCover')[0].files[0];
    if (coverFile) {
        formData.append('coverFile', coverFile);
    }
    
    // 验证逻辑
    if (!$('#editNovelTitle').val().trim()) {
        showError('请输入作品标题');
        return;
    }
    
    if (selectedCategories.length === 0) {
        showError('请选择作品分类');
        return;
    }
    
    if (!$('#editNovelIntro').val().trim()) {
        showError('请输入作品简介');
        return;
    }
    
    // 使用 PUT 方法更新作品
    $.ajax({
        url: `/demo1_war_exploded/API/Bookshelf/${novelId}`,
        type: 'PUT',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.code === 200) {
                bootstrap.Modal.getInstance(document.getElementById('editNovelModal')).hide();
                showSuccess('作品更新成功');
                loadAuthorNovels(); // 刷新作品列表
                loadAuthorStats(); // 刷新统计数据
            } else {
                showError(response.msg || '更新失败');
            }
        },
        error: function() {
            showError('网络错误，请稍后重试');
        }
    });
}